{% extends "layout/public.html" %}

{% block title %}首页{% endblock %}

{% block head %}
<style>
    /*上传区域*/
    .before-upload-area {
        position: absolute;
        left: 50%;
        top: 25%;
        transform: translate(-50%, -25%);
    }
    .layui-upload-area {
        border-radius: 20px;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    }
    .layui-upload-drag {
        background-color: transparent;
        padding: 20px;
    }
    .layui-upload-drag:hover {
        border:1px dotted #999;
    }
    /*上传表格*/
    table, tbody, tr, td {
        margin: 0;
        padding: 0;
        border: 0;
        border-spacing: 0;
    }
    .a { width: 55px; }
    .b { text-align:left; }
    .c { max-width: 50px; }
    .d { max-width: 50px; }
    .e { max-width: 80px; }
    .f { max-width: 150px; min-width: 80px; }
    .g { max-width: 80px; }
    .layui-layout-admin .layui-footer {
        line-height: initial;
        padding: 0;
    }
</style>
{% endblock %}

{% block content %}
        <div class="before-upload-area">{{ g.site.upload_beforehtml|safe }}</div>
        <div class="layui-upload-area">
            <div class="layui-upload-drag" id="upload">
                <i class="layui-icon layui-icon-upload"></i>
                <p>点击、粘贴或拖拽到此处上传<br>允许{{ (g.site.upload_exts or 'jpg|png|gif|bmp|jpeg|webp').split('|')|join(',') }}图片</p>
            </div>
            <div class="layui-upload-list">
                <button type="button" class="layui-btn layui-btn-xs layui-hide" id="action">开始上传</button>
                <table class="layui-table layui-hide" lay-size="sm">
                    <thead>
                        <tr>
                            <th class="a">预览</th>
                            <th class="b">文件</th>
                            <th class="c">大小(KB)</th>
                            <th class="d">状态</th>
                            <th class="e">进度</th>
                            <th class="f">相册</th>
                            <th class="g">操作</th>
                        </tr>
                    </thead>
                    <tbody id="previewList"></tbody>
                </table>
            </div>
        </div>
{% endblock %}

{% block script %}
{% include "ref/upload_show.html" %}
<script>
    layui.use(['picbed', 'layer', 'upload', 'laytpl', 'element'], function () {
        var $ = layui.jquery,
            picbed = layui.picbed,
            layer = layui.layer,
            upload = layui.upload,
            laytpl = layui.laytpl,
            element = layui.element;

        var exts = "{{ g.site.upload_exts or 'jpg|png|gif|bmp|jpeg|webp' }}",
            size = parseFloat("{{ g.site.upload_size or 10 }}"), //MB
            number = parseInt("{{ g.site.upload_number or 10 }}"),
            field = "{{ g.cfg.upload_field or 'picbed' }}",
            upviewDom = $('#previewList'),
            imgUrlRe = new RegExp("^(http[s]?://.*.(?:" + exts + "))$", "i");

        var showUploadCopy = function (res) {
            res["get_src"] = function() {
                return res.src;
            };
            laytpl(upload_show_tpl.innerHTML).render(res, function (html) {
                layer.open({
                    type: 1,
                    title: false,
                    closeBtn: true,
                    area: document.body.clientWidth > 550 ? '550px' : 'auto',
                    maxHeight: '500px',
                    shade: 0.1,
                    shadeClose: true,
                    skin: 'layui-layer-molv',
                    content: html,
                    success: function (layero, indexo) {
                        element.render('tab');
                        $(layero).find('.upload_show_copy').on('click', function () {
                            var copyId = $(this).data('copyid');
                            picbed.Clipboard.copy($(copyId).text());
                        });
                    }
                });
            });
        };

        var ajaxUpload = function (dataform) {
            dataform.append("album", "{{ request.args.album }}");
            dataform.append("origin", "homepage/{{ Version }}");

            /* 如果需要预览，可以执行下面代码
            var reader = new FileReader()
            reader.onload = function (event) {
                preview.innerHTML = '<img src="' + event.target.result + '" class="upload-image">';
            }
            reader.readAsDataURL(file);
            */

            // 不预览直接上传
            let index = layer.msg('上传中', {icon: 16,time: 5000});
            let xhr = new XMLHttpRequest();

            /* 上传进度
            if (xhr.upload) {
                xhr.upload.addEventListener('progress', function (event) {
                    let percent = Math.round(100 * event.loaded / event.total) / 100 + '%';
                }, false);
            }
            */

            // 上传结束
            xhr.onload = function () {
                layer.close(index);
                let res = JSON.parse(xhr.responseText);
                if (res.code === 0) {
                    layer.msg("上传成功", {
                        icon: 1,
                        time: 1000
                    }, function () {
                        showUploadCopy(res);
                    });
                } else {
                    layer.msg("上传失败：" + res.msg, {icon: 2});
                }
            };
            xhr.onerror = function () {
                layer.msg("网络异常，上传失败", {
                    icon: 2
                });
            };
            xhr.open('POST', '{{ url_for("api.upload") }}', true);
            try {
                xhr.send(dataform);
            } catch (e) {
                layer.msg(e.message, {icon: 2});
            };
        }

        //点击与拖拽上传
        var uploadListIns = upload.render({
            elem: '#upload',
            url: '{{ url_for("api.upload") }}',
            method: 'POST',
            data: {
                album: "{{ request.args.album }}",
                origin: "homepage/{{ Version }}"
            },
            accept: 'images',
            exts: exts,
            multiple: true,
            auto: false,
            bindAction: '#action',
            drag: true,
            field: field,
            number: number > 10 ? 10 : number,
            size: (size > 10 ? 10 : size) * 1024,
            updateData: function (index, data) {
                //改源码upload.js
                //typeof options.updateData === 'function' &&  options.updateData(index, options.data);
                data.album = $("#album-" + index).val();
            },
            choose: function (obj) {
                $(".before-upload-area").hide();
                var files = this.files = obj.pushFile();
                $("#action").removeClass("layui-hide");
                $(".layui-table:first").removeClass("layui-hide");
                obj.preview(function (index, file, result) {
                    var tr = $([
                        '<tr id="upload-' + index + '">',
                        '<td class="a"><img src="' + result + '" style="max-width:50px" class="layui-upload-img"></td>',
                        '<td class="b">' + (picbed.isMobile ? file.type.replace(/^image\//, '') : file.name) + '</td>',
                        '<td class="c">' + (file.size / 1024).toFixed(1) + '</td>',
                        '<td class="d">等待</td>',
                        '<td class="e"><div id="progress-' + index + '"></div></td>',
                        '<td class="f">{% if g.signin %}<input type="text" id="album-' + index + '" autocomplete="off" class="layui-input" value="{{ request.args.album }}">{% else %}<i class="layui-icon layui-icon-close"></i>{% endif %}</td>',
                        '<td class="g">',
                        '<button class="layui-btn layui-btn-xs upload-reload layui-hide">重传</button>',
                        '<button class="layui-btn layui-btn-xs layui-btn-danger upload-delete">删除</button>',
                        '</td>',
                        '</tr>'
                    ].join(''));
                    //单个重传
                    tr.find('.upload-reload').on('click', function () {
                        obj.upload(index, file);
                    });
                    //删除
                    tr.find('.upload-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        uploadListIns.config.elem.next()[0].value = '';
                    });
                    upviewDom.append(tr);
                });
            },
            before: function (obj) {
                if (Object.keys(this.files).length === 0) {
                    layer.msg("暂无图片等待上传！", {
                        icon: 1
                    });
                }
            },
            progress: function (index, v) {
                //改源码upload.js
                //options.progress(index, percent, options.item[0], e)
                $('#progress-' + index).text(v + '%');
            },
            done: function (res, index, upload) {
                if (res.code === 0) { //上传成功
                    var tr = upviewDom.find('tr#upload-' + index),
                        tds = tr.children();
                    tds.eq(3).html('<span style="color: #5FB878;">成功</span>');
                    tds.eq(6).html('<button class="layui-btn layui-btn-xs layui-btn-normal upload-show" data-index="' + index + '">查看</button>'); //清空操作
                    delete this.files[index]; //删除文件队列已经上传成功的文件
                    //layer.closeAll('loading');
                    tr.find('.upload-show').on('click', function () {
                        showUploadCopy(res);
                    });
                    return;
                } else {
                    var tip = Object.keys(res.errors).map(function(key) {
                        return key + ": " + res.errors[key];
                    }).join("&#10;");
                    this.error(index, upload, tip ? (res.msg + "&#10;" + tip) : res.msg);
                }
            },
            error: function (index, upload, err_msg) {
                var tr = upviewDom.find('tr#upload-' + index),
                    tds = tr.children();
                tds.eq(3).html('<span style="color: #FF5722;"><abbr title="' + err_msg + '">失败</abbr></span>');
                tds.eq(6).find('.upload-reload').removeClass('layui-hide'); //显示重传
                //layer.closeAll('loading');
            }
        });
        //粘贴上传
        document.addEventListener('paste', function (event) {
            let clipdata = event.clipboardData || window.clipboardData;
            let items = clipdata.items;
            let file = null;
            if (items && items.length) {
                // 搜索剪切板items
                for (let i = 0; i < items.length; i++) {
                    if (items[i].type.indexOf('image') !== -1) {
                        file = items[i].getAsFile();
                        break;
                    }
                }
            } else {
                layer.msg("当前浏览器不支持", {icon: 2});
                return;
            }
            if (file) {
                // 此时file就是我们的剪切板中的图片File对象
                //判断上传图片大小
                if (size > 0) {
                    if ((file.size / 1024) > (size * 1024)) {
                        layer.msg("粘贴图片超过限制大小【" + size + "KB】", {
                            icon: 0
                        });
                        return;
                    }
                }
                //判断上传图片后缀
                if (exts) {
                    let EXTRE = new RegExp("(" + exts + "$)", "i");
                    let _ext = file.name.split(".");
                    _ext = _ext[_ext.length - 1];
                    if (!EXTRE.test(_ext)) {
                        layer.msg("不支持的图片格式【" + _ext + "】", {
                            icon: 0
                        });
                        return;
                    }
                }

                let data = new FormData();
                data.append(field, file, file.name);
                ajaxUpload(data);
            } else {
                //简单判断是否是图片URL
                let maybeImgurl = (clipdata.getData('text/plain') || '').trim();
                if (imgUrlRe.test(maybeImgurl)) {
                    let data = new FormData();
                    data.append(field, maybeImgurl);
                    ajaxUpload(data);
                } else {
                    layer.msg("粘贴内容非图片", {icon: 0});
                }
            }
        });
    });
</script>
{% endblock %}